<template>
  <div class="knowledge-tag-container">
    <div class="page-header">
      <h2>知识库标签管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        新增标签
      </el-button>
    </div>

    <div class="content-wrapper">
      <!-- 搜索和筛选 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标签名称..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="filterStatus" placeholder="状态筛选" clearable style="width: 150px">
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>
        
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 标签列表 -->
      <el-table :data="filteredTags" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="标签名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="color" label="标签颜色" width="100">
          <template #default="{ row }">
            <el-tag :color="row.color" style="color: white; border: none;">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="使用次数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editTag(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === 'active' ? 'warning' : 'success'"
              @click="toggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteTag(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑标签对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingTag ? '编辑标签' : '新增标签'"
      width="500px"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        
        <el-form-item label="标签描述" prop="description">
          <el-input
            v-model="tagForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
          />
        </el-form-item>
        
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="tagForm.color" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="tagForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveTag">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const showAddDialog = ref(false)
const editingTag = ref<any>(null)

// 表单引用
const tagFormRef = ref()

// 标签表单
const tagForm = reactive({
  id: null,
  name: '',
  description: '',
  color: '#409EFF',
  status: 'active'
})

// 表单验证规则
const tagRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
}

// 模拟标签数据
const tags = ref([
  {
    id: 1,
    name: '常见问题',
    description: '用户经常遇到的问题',
    color: '#409EFF',
    count: 45,
    status: 'active',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    name: '操作指南',
    description: '系统操作相关指南',
    color: '#67C23A',
    count: 32,
    status: 'active',
    createTime: '2024-01-14 14:20:00'
  },
  {
    id: 3,
    name: '故障排除',
    description: '系统故障解决方案',
    color: '#E6A23C',
    count: 18,
    status: 'active',
    createTime: '2024-01-13 09:15:00'
  },
  {
    id: 4,
    name: '新功能',
    description: '系统新功能介绍',
    color: '#F56C6C',
    count: 8,
    status: 'inactive',
    createTime: '2024-01-12 16:45:00'
  }
])

// 计算属性
const filteredTags = computed(() => {
  let result = tags.value

  if (searchKeyword.value) {
    result = result.filter(tag => 
      tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      tag.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  if (filterStatus.value) {
    result = result.filter(tag => tag.status === filterStatus.value)
  }

  return result
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  // 这里可以调用API进行搜索
}

const resetSearch = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  currentPage.value = 1
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  // 重新加载数据
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  // 重新加载数据
}

const editTag = (tag: any) => {
  editingTag.value = tag
  Object.assign(tagForm, tag)
  showAddDialog.value = true
}

const saveTag = async () => {
  try {
    await tagFormRef.value.validate()
    
    if (editingTag.value) {
      // 编辑标签
      const index = tags.value.findIndex(t => t.id === editingTag.value.id)
      if (index !== -1) {
        tags.value[index] = { ...editingTag.value, ...tagForm }
      }
      ElMessage.success('标签更新成功')
    } else {
      // 新增标签
      const newTag = {
        ...tagForm,
        id: Date.now(),
        count: 0,
        createTime: new Date().toLocaleString()
      }
      tags.value.unshift(newTag)
      ElMessage.success('标签创建成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const toggleStatus = (tag: any) => {
  const action = tag.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}标签"${tag.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    tag.status = tag.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`标签${action}成功`)
  }).catch(() => {})
}

const deleteTag = (tag: any) => {
  ElMessageBox.confirm(
    `确定要删除标签"${tag.name}"吗？删除后不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = tags.value.findIndex(t => t.id === tag.id)
    if (index !== -1) {
      tags.value.splice(index, 1)
      ElMessage.success('标签删除成功')
    }
  }).catch(() => {})
}

const resetForm = () => {
  editingTag.value = null
  Object.assign(tagForm, {
    id: null,
    name: '',
    description: '',
    color: '#409EFF',
    status: 'active'
  })
  tagFormRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  total.value = tags.value.length
})
</script>

<style scoped>
.knowledge-tag-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.content-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
  }
}
</style>
